package lucene.server.database;

import lucene.server.database.meta.*;
import lucene.server.database.model.ColumnModel;
import lucene.server.database.model.DatabaseModel;
import lucene.server.database.model.TableModel;
import lucene.server.database.pool.PoolManager;
import lucene.server.database.utils.DialectUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DBMetaService {

    //系统配置的数据源（ConnName）为Key
    public static ConcurrentHashMap<String, Map<String,DatabaseModel>> databaseMap = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, IDialectMeta> dialectMap = new ConcurrentHashMap<>();

    public static Map<String,DatabaseModel> getDatabases(String connName,String connType){
        if (!databaseMap.containsKey(connName)){
            IDialectMeta dialectMeta = getDialectMeta(connType);
            databaseMap.put(connName,dialectMeta.getDataBases(PoolManager.getConnection(connName)));
        }
        return databaseMap.get(connName);
    }
    public static  DatabaseModel  getDatabase(String connName,String connType,String databaseName){
        return getDatabases(connName,connType).get(databaseName);
    }
    public static Map<String, TableModel> getTables(String connName, String connType, String databaseName){
        DatabaseModel databaseModel = getDatabase(connName,connType,databaseName);

        if (databaseModel.getTableMap().isEmpty()){
            getDialectMeta(connType).setTables(PoolManager.getConnection(connName),databaseModel);
        }
        return databaseModel.getTableMap();
    }

    public static TableModel getTable(String connName,String connType,String databaseName,String tableName){
        return getTables(connName,connType,databaseName).get(tableName);
    }
    public static List<ColumnModel> getColumns(String connName, String connType, String databaseName, String tableName){
            TableModel table = getTable(connName,connType,databaseName,tableName);
            if (table.getColumnsMap().isEmpty()){
                getDialectMeta(connType).setColumns(PoolManager.getConnection(connName),getDatabase(connName,connType,databaseName),table);
            }
            return table.getColumnsMap();
    }

    public static IDialectMeta getDialectMeta(String connType){
        connType = connType.toLowerCase();
        if(!dialectMap.containsKey(connType)){

            dialectMap.put(connType, DialectUtil.createDialectMeta(connType));
        }
        return  dialectMap.get(connType);
    }

}
